<!-- 登录页面 -->
<template>
  <view class="login-container">
    <!-- 顶部品牌区域 -->
    <view class="brand-section">
      <image class="logo" :src="sheep.$store('app').info.logo" mode="aspectFit"></image>
      <view class="app-name">{{ sheep.$store('app').info.name || '粤装饰' }}</view>
    </view>

    <!-- 登录表单区域 -->
    <view class="form-section">
      <!-- 账号密码登录表单 -->
      <view class="login-form">
        <view class="input-group">
          <uni-easyinput
            placeholder="请输入账号"
            v-model="loginForm.username"
            type="text"
            :inputBorder="false"
          />
        </view>
        <view class="input-group">
          <uni-easyinput
            placeholder="请输入密码"
            v-model="loginForm.password"
            type="password"
            :inputBorder="false"
          />
        </view>
        <view class="forgot-password" @tap="goToResetPassword">忘记密码</view>
        <button 
          class="login-button"
          @click="handleLogin"
          :loading="loading"
          :disabled="loading"
        >
          登录
        </button>
      </view>

      <!-- 用户协议 -->
      <view class="agreement-section">
        <checkbox-group @change="handleAgreementChange">
          <label>
            <checkbox value="agreement" :checked="agreementChecked" />
            <text>我已阅读并同意</text>
            <text class="agreement-link" @tap="goToAgreement">《用户协议》</text>
            <text>和</text>
            <text class="agreement-link" @tap="goToPrivacy">《隐私政策》</text>
          </label>
        </checkbox-group>
      </view>
    </view>
  </view>
</template>

<script setup>
  import { ref, reactive } from 'vue';
  import sheep from '@/sheep';
  import { onLoad } from '@dcloudio/uni-app';
  import AuthUtil from '@/sheep/api/member/auth';
  import { mobile, password } from '@/sheep/validate/form';
  
  // 登录表单
  const loginForm = reactive({
    username: '',
    password: '',
    tenantId: ''
  });
  
  // 协议勾选状态
  const agreementChecked = ref(true);
  
  // 加载状态
  const loading = ref(false);
  
  // 处理账号密码登录
  const handleLogin = async () => {
    // 验证账号
    // if (!mobile.validator(loginForm.username)) {
    //   sheep.$helper.toast('请输入正确的账号');
    //   return;
    // }

    if (!loginForm.username) {
      sheep.$helper.toast('请输入账号');
      return;
    }

    // 验证密码
    if (!password.validator(loginForm.password)[0]) {
      sheep.$helper.toast(password.validator(loginForm.password)[1]);
      return;
    }
    
    // 验证协议
    if (!agreementChecked.value) {
      sheep.$helper.toast('请阅读并同意用户协议和隐私政策');
      return;
    }
    
    try {
      loading.value = true;
      console.log('开始发送登录请求:', loginForm);
      const { code, data } = await AuthUtil.login(loginForm);
      console.log('登录请求结果:', { code, data });
      if (code === 0) {
        // 登录成功，设置token并跳转
        // const userStore = sheep.$store('user');
        // userStore.setToken(data.token, data.refreshToken);
        
        // 检查是否有返回地址
        const returnUrl = uni.getStorageSync('returnUrl');
        if (returnUrl) {
          uni.removeStorageSync('returnUrl');
          // #ifdef H5
          location.replace(returnUrl);
          // #endif
          // #ifndef H5
          uni.navigateTo({ url: returnUrl });
          // #endif
        } else {
          uni.switchTab({ url: '/' });
        }
      }
    } catch (error) {
      console.error('登录失败:', error);
      sheep.$helper.toast('登录失败，请稍后重试');
    } finally {
      loading.value = false;
    }
  };
  
  // 处理协议勾选变化
  const handleAgreementChange = (e) => {
    agreementChecked.value = e.detail.value.includes('agreement');
  };
  
  // 跳转到重置密码页面
  const goToResetPassword = () => {
    sheep.$router.go('/pages/public/richtext', { title: '重置密码' });
  };
  
  // 跳转到用户协议
  const goToAgreement = () => {
    sheep.$router.go('/pages/public/richtext', { title: '用户协议' });
  };
  
  // 跳转到隐私政策
  const goToPrivacy = () => {
    sheep.$router.go('/pages/public/richtext', { title: '隐私政策' });
  };
  
  // 保留原来的回调逻辑
  onLoad(async (options) => {
    // #ifdef H5
    // 将 search 参数赋值到 options 中，方便下面解析
    new URLSearchParams(location.search).forEach((value, key) => {
      options[key] = value;
    });
    // 执行登录 or 绑定，注意需要 await 绑定
    const event = options.event;
    const code = options.code;
    const state = options.state;
    if (event === 'login') { // 场景一：登录
      try {
        await sheep.$platform.useProvider().login(code, state);
        
        // 检测 H5 登录回调
        let returnUrl = uni.getStorageSync('returnUrl');
        if (returnUrl) {
          uni.removeStorageSync('returnUrl');
          location.replace(returnUrl);
        } else {
          uni.switchTab({
            url: '/',
          });
        }
      } catch (error) {
        console.error('回调登录失败:', error);
      }
    } else if (event === 'bind') { // 场景二：绑定
      try {
        await sheep.$platform.useProvider().bind(code, state);
        
        // 检测 H5 登录回调
        let returnUrl = uni.getStorageSync('returnUrl');
        if (returnUrl) {
          uni.removeStorageSync('returnUrl');
          location.replace(returnUrl);
        } else {
          uni.switchTab({
            url: '/',
          });
        }
      } catch (error) {
        console.error('回调绑定失败:', error);
      }
    }
    // #endif
  });
</script>

<style lang="scss" scoped>
  .login-container {
    padding: 50rpx 34rpx;
    min-height: 100vh;
    background-color: #f7f7f7;
    display: flex;
    flex-direction: column;
  }
  
  .brand-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 80rpx;
    margin-top: 50rpx;
  }
  
  .logo {
    width: 180rpx;
    height: 180rpx;
    margin-bottom: 30rpx;
    background-color: #fff;
    border-radius: 20rpx;
    padding: 10rpx;
  }
  
  .app-name {
    font-size: 40rpx;
    font-weight: bold;
    color: #333333;
  }
  
  .form-section {
    flex: 1;
  }
  
  .login-form {
    background-color: #fff;
    border-radius: 20rpx;
    padding: 40rpx 30rpx;
  }
  
  .input-group {
    margin-bottom: 40rpx;
    position: relative;
  }
  
  .input-group::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 2rpx;
    background-color: #f0f0f0;
  }
  
  .forgot-password {
    text-align: right;
    font-size: 28rpx;
    color: #0081ff;
    margin: -20rpx 0 30rpx 0;
  }
  
  .login-button {
    width: 100%;
    height: 90rpx;
    line-height: 90rpx;
    background-color: #0081ff; // 使用海蓝色代替未定义的CSS变量
    border-radius: 45rpx;
    font-size: 32rpx;
    font-weight: 500;
    color: #ffffff;
    margin-top: 30rpx;
  }
  
  .agreement-section {
    margin-top: 30rpx;
    padding: 0 10rpx;
  }
  
  .agreement-section checkbox-group {
    display: flex;
    justify-content: center;
  }
  
  .agreement-section label {
    display: flex;
    align-items: center;
    font-size: 26rpx;
    color: #999999;
  }
  
  .agreement-section checkbox {
    transform: scale(0.7);
    margin-right: 10rpx;
  }
  
  .agreement-link {
    color: var(--ui-BG-Main);
  }
</style>
